// Cloudflare Worker 代码 - 简书 RSS 生成器
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
const path = url.pathname
// 设置 CORS 头
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/xml; charset=utf-8'
}
// 处理简书用户文章 RSS
if (path.startsWith('/jianshu/user/')) {
const userId = path.split('/').pop()
return await generateJianshuRSS(userId, headers)
}
// 首页提示
return new Response(`
🎉 RSSHub Cloudflare Worker 运行中!
使用方式:/jianshu/user/作者ID
示例:https://你的域名/jianshu/user/e5093f04e510
`, { headers: { 'Content-Type': 'text/html' } })
}
async function generateJianshuRSS(userId, headers) {
try {
// 获取用户文章列表
const apiUrl = `https://www.jianshu.com/users/${userId}/timeline`
const response = await fetch(apiUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
}
})
if (!response.ok) {
throw new Error('Failed to fetch user data')
}
const html = await response.text()
// 解析文章数据(从 HTML 中提取)
const articles = parseArticles(html, userId)
if (articles.length === 0) {
throw new Error('No articles found')
}
// 生成 RSS XML
const rssXml = generateRSS(articles, userId)
return new Response(rssXml, { headers })
} catch (error) {
return new Response(`${error.message}`, {
status: 500,
headers
})
}
}
function parseArticles(html, userId) {
const articles = []
// 使用正则提取文章信息
const titleRegex = /([^<]+)<\/a>/g
const timeRegex = //g
let match
const titles = []
const times = []
while ((match = titleRegex.exec(html)) !== null) {
titles.push({
id: match[1],
title: match[2].trim()
})
}
while ((match = timeRegex.exec(html)) !== null) {
times.push(match[1])
}
// 合并数据(取前10篇)
for (let i = 0; i < Math.min(titles.length, times.length, 10); i++) {
articles.push({
title: titles[i].title,
link: `https://www.jianshu.com/p/${titles[i].id}`,
pubDate: new Date(times[i]).toUTCString(),
guid: titles[i].id
})
}
return articles
}
function generateRSS(articles, userId) {
const now = new Date().toUTCString()
let items = articles.map(article => `
-
${article.link}
${article.guid}
${article.pubDate}
`).join('')
return `
简书用户 ${userId} 的文章
https://www.jianshu.com/u/${userId}
简书用户文章 RSS 订阅
${now}
zh-CN
${items}
`
}